import io from 'socket.io-client';
import PubSub from 'pubsub.js'
import {localStorage} from  './localStorage'
function WS(){
  this.disLinkNumber = 0;
  this.isClientSocket = true;
  this.addEventSocketFlag = true;
  this.arr=[]

  this.onCenten = () => {
    this.disLinkNumber = 0;
    this.addEventSocketFlag = true;
    if(this.isClientSocket){
      this.isClientSocket = false;
      this.socket = io("http://192.168.0.226:9585", {
        query: {
          "currentUserId": localStorage.get("userID"),
        },
        //是否自动重新连接
        reconnection: true,
        //放弃前重新连接的次数
        reconnectionAttempts: 11,
        //默认初始的延长时间
        reconnectionDelay: 10000,
        // randomizationFactor: 1,
        //重新连接等待的最长时间
        reconnectionDelayMax: 30000,
      });

    }else{
      this.emitPair()
    }
    this.addEventSocket();
    this.wsReceiveSocket();
  }
  this.addEventSocket = () =>{
    if(this.socket){
      //连接超时时触发connect_timeout事件
      this.socket.on('connect_timeout', function(timeout){
        console.log('链接超时 - connect_timeout');
      });
       //连接断开disconnect事件
      this.socket.on('disconnect', reason => {
        if(this.disLinkNumber <= 10 && this.addEventSocketFlag){
          setTimeout(()=>{
            //重新连接事件reconnect 重新连接尝试编号
            this.socket.on('reconnect',(attemptNumber) => {

            })
            this.socket.open();
          },1000 * 5)
        }
        this.disLinkNumber ++;
      })
    }
  }

  this.emitPair = () => {
    if(this.socket){
      this.socket.emit('push_event',(data)=>{
        // console.log(data,"第一个")
      })
    }
  }

  // 监听
  this.wsReceiveSocket = () => {
    //判断socket是否连接服务器成功
    this.socket.on('connect', () => {
      // console.log(socket.connected); //true为连接成功
      this.socket.on("broadcast",res=>{
        // if(res.content){
        //   this.arr.push(res)
        // }
        // let  hash={};
        // this.arr=this.arr.reduce(function (item,next) {
        //   hash[next.content] ? '' :hash[next.content] = true && item.push(next)
        //   return item
        // },[])

        // console.log(this.arr,"是数组吗")
        PubSub.publish("socketData",res.content)
      })
    })
  }

  // 关闭 scoket  前后端约定的字段
  this.wsCloseSocket = () => {
    if(this.socket){
      this.addEventSocketFlag = false;
      this.socket.emit('discontent',(data)=>{

      })
    }
  }
 this.closeSocket=()=>{
    if(this.socket){

      socket.close()
    }
 }

  // 订阅 scoket
  // this.watchScoket = FN => {
  //   PubSub.subscribe('aa', (msg,data) => {
  //     // console.log(msg,data,"订阅的数据")
  //     FN(data)
  //   })
  // }
}

const socket = new WS()
export default socket
